package forms;

import classes.Conexao;
import classes.Utilitarios;
import java.sql.ResultSet;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author Yanni
 */
public class FormCadastrarFuncionario extends javax.swing.JInternalFrame {

    private String textoPermitido = "abcdefghijklmnopqrstuvwxyzçáéíóúâêôàèãõñ ";
    /**
     * Creates new form FormCadastrarFuncionario
     */
    Utilitarios u = new Utilitarios();

    public FormCadastrarFuncionario()
    {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        lblNmFuncionario = new javax.swing.JLabel();
        txtNmFuncionario = new javax.swing.JTextField(new classes.CaracteresPermitidos(textoPermitido + textoPermitido.toUpperCase()), "", 30);
        lblCdCpfFuncionario = new javax.swing.JLabel();
        txtCdCpfFuncionario = new javax.swing.JFormattedTextField();
        lblCdTelefoneFuncionario = new javax.swing.JLabel();
        txtCdTelefoneFuncionario = new javax.swing.JFormattedTextField();
        lblCdUsuario = new javax.swing.JLabel();
        btnLimpar = new javax.swing.JButton();
        btnCadastrar = new javax.swing.JButton();
        btnPesquisar = new javax.swing.JButton();
        txtNmCargo = new javax.swing.JTextField(new classes.CaracteresPermitidos(textoPermitido + textoPermitido.toUpperCase()), "", 20);
        lblNmCargo = new javax.swing.JLabel();
        cmbNmUsuario = new javax.swing.JComboBox();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cadastrar Funcionário");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener()
        {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt)
            {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt)
            {
                formInternalFrameOpened(evt);
            }
        });

        lblNmFuncionario.setText("Nome:");

        txtNmFuncionario.setToolTipText("Digite o nome do funcionário");

        lblCdCpfFuncionario.setText("CPF:");

        try
        {
            txtCdCpfFuncionario.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex)
        {
            ex.printStackTrace();
        }
        txtCdCpfFuncionario.setToolTipText("Digite o CPF do funcionário");

        lblCdTelefoneFuncionario.setText("Telefone:");

        try
        {
            txtCdTelefoneFuncionario.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) ####-####")));
        } catch (java.text.ParseException ex)
        {
            ex.printStackTrace();
        }
        txtCdTelefoneFuncionario.setToolTipText("Digite o telefone do funcionário");

        lblCdUsuario.setText("Usuário:");

        btnLimpar.setText("Limpar");
        btnLimpar.setToolTipText("Clique aqui para limpar os valores");
        btnLimpar.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnLimparActionPerformed(evt);
            }
        });

        btnCadastrar.setText("Cadastrar");
        btnCadastrar.setToolTipText("Clique aqui para cadastrar o funcionário");
        btnCadastrar.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnCadastrarActionPerformed(evt);
            }
        });

        btnPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/procurar.png"))); // NOI18N
        btnPesquisar.setToolTipText("Clique aqui para pesquisar o usuário");
        btnPesquisar.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnPesquisarActionPerformed(evt);
            }
        });

        txtNmCargo.setToolTipText("Digite o cargo do funcionário");

        lblNmCargo.setText("Cargo:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblCdUsuario)
                            .addComponent(lblCdTelefoneFuncionario)
                            .addComponent(lblCdCpfFuncionario)
                            .addComponent(lblNmFuncionario)
                            .addComponent(lblNmCargo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNmFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCdCpfFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCdTelefoneFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNmCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmbNmUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(26, 26, 26)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addComponent(btnCadastrar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNmFuncionario)
                    .addComponent(txtNmFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNmCargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNmCargo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCdCpfFuncionario)
                    .addComponent(txtCdCpfFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCdTelefoneFuncionario)
                    .addComponent(txtCdTelefoneFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnPesquisar)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblCdUsuario)
                        .addComponent(cmbNmUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCadastrar)
                    .addComponent(btnLimpar))
                .addGap(74, 74, 74))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-399)/2, (screenSize.height-325)/2, 399, 325);
    }// </editor-fold>//GEN-END:initComponents

    private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
        u.limparTextFields(this);
        txtCdCpfFuncionario.setValue("");
        txtCdTelefoneFuncionario.setValue("");
        txtNmFuncionario.requestFocus();
    }//GEN-LAST:event_btnLimparActionPerformed

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnPesquisarActionPerformed
    {//GEN-HEADEREND:event_btnPesquisarActionPerformed
        FormSelecionarUsuario fsu = new FormSelecionarUsuario();
        this.getDesktopPane().add(fsu);
        fsu.setFrameIcon(new ImageIcon(getClass().getResource("/imagens/icon.png")));
        fsu.setVisible(true);
    }//GEN-LAST:event_btnPesquisarActionPerformed

    private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnCadastrarActionPerformed
    {//GEN-HEADEREND:event_btnCadastrarActionPerformed
        String nome,cargo, cpf, tel, user, sql;
        int codUser = 0;
        
        try
        {
            nome = txtNmFuncionario.getText();
            cargo = txtNmCargo.getText();
            cpf = txtCdCpfFuncionario.getText();//pega o valor
            tel = txtCdTelefoneFuncionario.getText();
            user = cmbNmUsuario.getSelectedItem().toString();

            cpf = cpf.replaceAll("\\.", "").replaceAll("-", "");//tira os pontos e o traço
            tel = tel.replaceAll("\\(", "").replaceAll("\\)", "").replaceAll("-", "").replaceAll(" ", "");
            
            sql = "SELECT cd_usuario FROM usuario WHERE nm_login_usuario = '" + user + "'";
            
            ResultSet rs = Conexao.consultar(sql);
            
            while (rs.next()) {
                codUser = rs.getInt("cd_usuario");
            }
            
            sql = "INSERT INTO funcionario VALUES(FUNCIONARIO_SEQ.NEXTVAL, UPPER('" + nome + "'), " + tel + ", " + cpf + ", UPPER('" + cargo + "'), " + codUser + ")";
            
            if (Conexao.atualizar(sql) == -1)
            {
                JOptionPane.showMessageDialog(null, "O registro não pode ser inserido: \n" + Conexao.getErro(), "Cadastro", 0);
                btnLimparActionPerformed(evt);
                formInternalFrameOpened(null);
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Cadastrado com sucesso.", "Cadastro", 1);
                btnLimparActionPerformed(evt);
                formInternalFrameOpened(null);
            }
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(this, "Erro: \n" + e.getMessage(), "Erro!", 0);
            u.limparTextFields(this);
        }
    }//GEN-LAST:event_btnCadastrarActionPerformed

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt)//GEN-FIRST:event_formInternalFrameOpened
    {//GEN-HEADEREND:event_formInternalFrameOpened
        DefaultComboBoxModel combo = (DefaultComboBoxModel) cmbNmUsuario.getModel();
        combo.removeAllElements();

        try
        {
            String sql = "SELECT nm_login_usuario FROM usuario WHERE cd_usuario NOT IN"
                    + "(SELECT cd_usuario FROM funcionario)";
            ResultSet res = Conexao.consultar(sql);

            if (Conexao.consultar(sql) == null)
            {
                JOptionPane.showMessageDialog(null, "Erro na consulta: \n" + Conexao.getErro(), "Erro!", 0);
            }
            else
            {
                if (Conexao.consultar(sql).next())
                {
                    while (res.next())
                    {
                        combo.addElement(res.getString("nm_login_usuario"));
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Nenhum usuário disponível encontrado.\nCadastre mais usuários.", "Aviso!", 2);
                    this.dispose();
                }
            }
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "Erro na consulta: \n" + e.getMessage(), "Erro!", 0);
        }
    }//GEN-LAST:event_formInternalFrameOpened
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCadastrar;
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JComboBox cmbNmUsuario;
    private javax.swing.JLabel lblCdCpfFuncionario;
    private javax.swing.JLabel lblCdTelefoneFuncionario;
    private javax.swing.JLabel lblCdUsuario;
    private javax.swing.JLabel lblNmCargo;
    private javax.swing.JLabel lblNmFuncionario;
    private javax.swing.JFormattedTextField txtCdCpfFuncionario;
    private javax.swing.JFormattedTextField txtCdTelefoneFuncionario;
    private javax.swing.JTextField txtNmCargo;
    private javax.swing.JTextField txtNmFuncionario;
    // End of variables declaration//GEN-END:variables
}
